//
//  HNHappyFamilyTVController.m
//  XDEducation
//
//  Created by 星道 on 17/6/6.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HNHappyFamilyTVController.h"
#import "HNHappyFamilyTVCell.h"
#import "HNHappyFamilyTVModel.h"
#import "WMPlayer.h"
#import "AppDelegate.h"
@interface HNHappyFamilyTVController ()<UICollectionViewDelegateFlowLayout,WMPlayerDelegate>
/** 页数 */
@property (nonatomic, assign) NSInteger Index;
/** 数据存存储 */
@property (nonatomic, strong) NSMutableArray <HNHappyFamilyTVModel *>*DataArr;

//视频播放
@property (nonatomic, strong) WMPlayer *Player;
@property (nonatomic, strong) AppDelegate *Appdelegate;

//已播放时长，当达长限制时长时将不在允许播放
@property (nonatomic, assign) NSInteger PlayTime;
@end

@implementation HNHappyFamilyTVController


#pragma mark - 网络请求
- (void)RefreshData
{
    NSDictionary *Params = @{
                             @"action"  :@"getfilmHall",
                             @"page"    :@(self.Index),
                             @"formCode":@"XXDD_XXSQ_QJZDY_YSJT_DSDY",
                             };
    [XDHttpTool get:BaseURL(@"media.do") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:Params success:^(id responseObj) {

        [self EndRefresh];
        if ([responseObj[@"dataList"] isKindOfClass:[NSArray class]])
        {
            for (NSDictionary *Dict in responseObj[@"dataList"])
            {
                HNHappyFamilyTVModel *Model = [HNHappyFamilyTVModel mj_objectWithKeyValues:Dict];
                Model.SeePlay = @(10);
                [self.DataArr addObject:Model];
            }
            self.Index += 1;
            [self.collectionView reloadData];
        }
        else
        {
            [MBProgressHUD showError:responseObj[@"msg"]];
        }
    } failure:^(NSError *error) {
        [self EndRefresh];
        [MBProgressHUD showError:XDNetWorkError];
    }];
}

/** 结束刷新 */
- (void)EndRefresh
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    });
}


#pragma mark - CollectionView代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HNHappyFamilyTVCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = self.DataArr[indexPath.item];
    return Cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self VideoPlayWithTVModel:self.DataArr[indexPath.item]];
}

#pragma mark - AVPlayer视频代理
//横屏
- (void)HengPing
{
    //强制旋转横屏
    self.Appdelegate.allowRotation = 1;
    //强制翻转屏幕，Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
    self.Player.frame = CGRectMake(0, 0, ScreenW, ScreenH);
}
//竖屏
- (void)ShuPing
{
    //强制旋转竖屏
    self.Appdelegate.allowRotation = 0;
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
    [self.Player removeFromSuperview];
    self.Player = nil;
}

/** 停止播放并退出界面 */
-(void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn
{
    [self ShuPing];
}



#pragma mark - Function
/** 建立一个视频View加载到Window上并横屏 */
- (void)VideoPlayWithTVModel:(HNHappyFamilyTVModel *)Model
{
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:self.Player];
    [self.Player setURLString:Model.absoluteUrl];
    //切换成横屏
    [self HengPing];
    //开始播放
    [self.Player play];

    //限制孩子播放时间
    if ([[AccountTool shareAccountTool].currentAccount.rolecode isEqualToString:@"4"])
    {
        //开始计时，每一秒获取播放状态，正常播放计时器加1，达达限制时取消播放
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(PlayerTimer:) userInfo:Model repeats:YES];
    }
}

/** 播放循环 */
- (void)PlayerTimer:(NSTimer *)Timer
{
    HNHappyFamilyTVModel *Model = (HNHappyFamilyTVModel *)Timer.userInfo;
    //播放器处于播放状态
    if (self.Player.state == WMPlayerStatePlaying)
    {
        self.PlayTime += 1;
        //如果播放时长等于对象的可播放时间，说明到达限制的播放，要停止播放
        if (self.PlayTime == [Model.SeePlay integerValue])
        {
            //停止播放
            [self.Player pause];
            //停止计时
            [Timer invalidate];
            //已看时长清零
            self.PlayTime = 0;
            //提示
            [self AlertShow:@"温馨提示" Message:@"您的播放时长已用完,即将关闭播放器                                                                            " handler:^(UIAlertAction *action) {
                //关闭播放器并竖屏
                [self ShuPing];
            }];
        }
    }
}



/** AlertController */
- (void)AlertShow:(NSString *)Title Message:(NSString *)Message handler:(void (^ __nullable)(UIAlertAction *action))handler
{
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:Title message:Message preferredStyle:(UIAlertControllerStyleAlert)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDestructive) handler:handler]];
    [self presentViewController:Alert animated:YES completion:nil];
}





#pragma mark - Setter
- (NSMutableArray<HNHappyFamilyTVModel *> *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}


- (WMPlayer *)Player
{
    if (!_Player)
    {
        CGFloat x = 0;
        CGFloat y = 0;
        CGFloat w = ScreenW;
        CGFloat h = ScreenH
        ;
        _Player = [[WMPlayer alloc] initWithFrame:CGRectMake(x, y, w, h)];
        _Player.delegate = self;
        _Player.enableVolumeGesture = YES;//打开手控音乐调整
    }
    return _Player;
}

- (AppDelegate *)Appdelegate
{
    if (!_Appdelegate)
    {
        _Appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    }
    return _Appdelegate;
}




















#pragma mark - 初始化
- (instancetype)init
{
    //布局
    UICollectionViewFlowLayout *FlowLayout = [[UICollectionViewFlowLayout alloc] init];
    //大小
    FlowLayout.itemSize = CGSizeMake((ScreenW-30)/2, (ScreenW-30)/2*1.45);
    //间距
    FlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:FlowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.title = @"电视电影";

    //注册
    [self.collectionView registerNib:[UINib nibWithNibName:[HNHappyFamilyTVCell description] bundle:nil] forCellWithReuseIdentifier:@"Cell"];

    self.Index = 1;

    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        [self RefreshData];
    }];

    [self.collectionView.mj_footer beginRefreshing];

    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self AlertShow:@"该功能尚处于调试阶，孩子角色观看所有视频限制播放10秒" Message:@"安卓端视频无法播放/下载，暂无法将已观看时长的数据传递" handler:nil];
}





#pragma mark - 滑动动画
/** 设置CollectionView在滑动时隐藏Navigation */
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset

{

    if(velocity.y>0)

    {

        [self.navigationController setNavigationBarHidden:YES animated:YES];

    }

    else

    {

        [self.navigationController setNavigationBarHidden:NO animated:YES];

    }

}

@end
